import json
import os
import re
import shutil

from core.ReadExcel import get_repo_info, read_libraries_from_excel, fuzzy_match_libraries
from utils import config


def _run_config_scripts():
    """运行配置脚本"""
    print("开始更新项目配置...")

    # 重新导入以确保获取最新的值
    from utils.config import selected_sdk_version, selected_api_version

    if not selected_sdk_version or not selected_api_version:
        print("错误：未设置SDK版本，请确保在主程序开始时输入了正确的SDK版本")
        return

    # 处理hvigor目录和oh-package.json5文件
    _process_hvigor_and_oh_package(selected_sdk_version)

    # 执行特定库的额外配置
    _run_library_specific_scripts()
    print("项目配置更新完成")

def _process_hvigor_and_oh_package(sdk_version):
    """处理hvigor目录和oh-package.json5文件"""
    try:
        # 处理hvigor目录
        hvigor_dir = os.path.join(os.getcwd(), 'hvigor')
        if os.path.exists(hvigor_dir):
            # 删除hvigor-wrapper.js
            hvigor_wrapper_path = os.path.join(hvigor_dir, 'hvigor-wrapper.js')
            if os.path.exists(hvigor_wrapper_path):
                os.remove(hvigor_wrapper_path)
                print(f"已删除 {hvigor_wrapper_path}")

            # 修改hvigor-config.json5
            hvigor_config_path = os.path.join(hvigor_dir, 'hvigor-config.json5')
            if os.path.exists(hvigor_config_path):
                with open(hvigor_config_path, 'r', encoding='utf-8') as f:
                    hvigor_config_content = f.read()

                # 删除hvigorVersion字段和@ohos/hvigor-ohos-plugin字段
                hvigor_config_content = re.sub(r'"hvigorVersion":\s*"[^"]*",?\s*', '', hvigor_config_content)
                hvigor_config_content = re.sub(r'"@ohos/hvigor-ohos-plugin":\s*"[^"]*",?\s*', '', hvigor_config_content)

                # 添加或更新modelVersion
                hvigor_config_content = _add_or_update_model_version(hvigor_config_content, f"{sdk_version}")

                # 写回文件
                with open(hvigor_config_path, 'w', encoding='utf-8') as f:
                    f.write(hvigor_config_content)

                print(f"已更新 {hvigor_config_path}")

        # 修改工程级oh-package.json5
        oh_package_path = os.path.join(os.getcwd(), 'oh-package.json5')
        if os.path.exists(oh_package_path):
            with open(oh_package_path, 'r', encoding='utf-8') as f:
                oh_package_content = f.read()

            # 添加或更新modelVersion
            oh_package_content = _add_or_update_model_version(oh_package_content, f"{sdk_version}")

            # 写回文件
            with open(oh_package_path, 'w', encoding='utf-8') as f:
                f.write(oh_package_content)

            print(f"已更新 {oh_package_path}")
        print("项目配置修改成功")

    except Exception as e:
        print(f"处理hvigor目录和oh-package.json5时出错: {str(e)}")
        return False


def _add_or_update_model_version(content, version):
    """添加或更新modelVersion字段"""
    # 检查是否已存在modelVersion字段
    if '"modelVersion"' in content:
        # 更新现有的modelVersion
        content = re.sub(
            r'"modelVersion"\s*:\s*"[^"]*"',
            f'"modelVersion": "{version}"',
            content
        )
    else:
        # 在第一个大括号后添加modelVersion字段
        content = re.sub(
            r'{\s*',
            f'{{\n  "modelVersion": "{version}",\n  ',
            content,
            count=1
        )

    return content

def _get_current_library_name(specific_libraries=None):
    """获取当前库名（基于当前工作目录）
    Args:
        specific_libraries: 可选参数，指定要优先检查的库列表
    """
    try:
        # 从当前目录名称推断
        current_dir = os.path.basename(os.getcwd())

        # 获取所有库名
        libraries, _, _ = read_libraries_from_excel()
        
        # 如果指定了特定库，则优先检查这些库
        if specific_libraries:
            for lib in specific_libraries:
                if isinstance(lib, dict) and 'name' in lib:
                    lib_name = lib['name']
                else:
                    lib_name = lib
                
                if lib_name.lower() == current_dir.lower():
                    print(f"通过特定库列表匹配到库: {lib_name}")
                    return lib_name

        # 首先尝试直接匹配当前目录与库名
        for lib in libraries:
            if lib.lower() == current_dir.lower():
                print(f"通过目录名精确匹配到库: {lib}")
                return lib

        # 如果没有精确匹配，尝试部分匹配
        for lib in libraries:
            if lib.lower() in current_dir.lower() or current_dir.lower() in lib.lower():
                print(f"通过目录名部分匹配到库: {lib}")
                return lib

        # 尝试通过仓库名或子目录匹配
        for lib in libraries:
            owner, name, sub_dir = get_repo_info(lib)
            # 检查仓库名是否匹配
            if name and name.lower() == current_dir.lower():
                print(f"通过仓库名匹配到库: {lib}")
                return lib
            # 检查子目录是否匹配
            if sub_dir and sub_dir.lower() == current_dir.lower():
                print(f"通过子目录匹配到库: {lib}")
                return lib

        # 尝试模糊匹配
        matched_libraries = fuzzy_match_libraries(current_dir)
        if matched_libraries:
            print(f"通过模糊匹配到库: {matched_libraries[0]}")
            return matched_libraries[0]

        print("警告: 无法确定当前库名")
        return None

    except Exception as e:
        print(f"获取当前库名时出错: {str(e)}")
        return None

def _modify_build_profile(sdk_version, api_version):
    """修改build-profile.json5文件，更新SDK版本配置"""
    try:
        build_profile_path = os.path.join(os.getcwd(), 'build-profile.json5')
        if not os.path.exists(build_profile_path):
            print(f"警告：找不到build-profile.json5文件: {build_profile_path}")
            return False
        # 读取文件内容
        with open(build_profile_path, 'r', encoding='utf-8') as f:
            content = f.read()
        # 尝试解析JSON5（这里简化处理，将JSON5视为JSON）
        try:
            # 移除注释行
            content_clean = clean_json5_content(content)
            config = json.loads(content_clean)
            # 修改app层级的配置
            if 'app' in config:
                # 删除app层级的compileSdkVersion和compatibleSdkVersion
                if 'compileSdkVersion' in config['app']:
                    del config['app']['compileSdkVersion']
                if 'compatibleSdkVersion' in config['app']:
                    del config['app']['compatibleSdkVersion']
                # 修改products配置
                if 'products' in config['app']:
                    for product in config['app']['products']:
                        # 设置product层级的compatibleSdkVersion和runtimeOS
                        product['compatibleSdkVersion'] = 12
                        product['compileSdkVersion'] = 12
                        product['runtimeOS'] = "OpenHarmony"
                        product['signingConfig'] = "default"
            # 将修改后的配置写回文件
            with open(build_profile_path, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=2)  # type: ignore
            print(f"成功修改build-profile.json5文件")
        except json.JSONDecodeError as e:
            # 如果JSON解析失败，使用正则表达式方法
            print(f"JSON解析失败，使用正则表达式方法: {str(e)}")
            # 删除compileSdkVersion和targetSdkVersion
            content = re.sub(r',?\s*"compileSdkVersion"\s*:\s*\d+', '', content)
            content = re.sub(r',?\s*"targetSdkVersion"\s*:\s*\d+', '', content)
            # 修改compatibleSdkVersion
            content = re.sub(
                r'"compatibleSdkVersion"\s*:\s*\d+',
                '"compatibleSdkVersion": 12',
                content
            )

            # 修改runtimeOS
            if '"runtimeOS"' in content:
                content = re.sub(
                    r'"runtimeOS"\s*:\s*"[^"]*"',
                    '"runtimeOS": "OpenHarmony"',
                    content
                )
            else:
                # 如果没有runtimeOS字段，在compatibleSdkVersion后添加
                content = re.sub(
                    r'("compatibleSdkVersion"\s*:\s*"[^"]*")(\s*)(,?)',
                    r'\1,\n        "runtimeOS": "OpenHarmony"\3',
                    content
                )
            # 写回文件
            with open(build_profile_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"成功使用正则表达式修改build-profile.json5文件")

        # 处理entry目录下的build-profile.json5文件
        entry_build_profile_path = os.path.join(os.getcwd(), 'entry', 'build-profile.json5')
        if os.path.exists(entry_build_profile_path):
            with open(entry_build_profile_path, 'r', encoding='utf-8') as f:
                entry_content = f.read()
            
            # 尝试解析JSON5
            try:
                entry_content_clean = clean_json5_content(entry_content)
                entry_config = json.loads(entry_content_clean)
                
                # 处理targets数组中的runtimeOS字段
                if 'app' in entry_config and 'targets' in entry_config['app']:
                    for target in entry_config['app']['targets']:
                        if 'runtimeOS' in target:
                            del target['runtimeOS']
                            print(f"已从entry目录的build-profile.json5中移除targets层级的runtimeOS字段")
                
                # 写回文件
                with open(entry_build_profile_path, 'w', encoding='utf-8') as f:
                    json.dump(entry_config, f, indent=2)
            except json.JSONDecodeError:
                # 如果JSON解析失败，使用正则表达式方法
                entry_content = re.sub(r',?\s*"runtimeOS"\s*:\s*"[^"]*"', '', entry_content)
                with open(entry_build_profile_path, 'w', encoding='utf-8') as f:
                    f.write(entry_content)
                print(f"已使用正则表达式从entry目录的build-profile.json5中移除runtimeOS字段")
    except Exception as e:
        print(f"修改build-profile.json5文件时出错: {str(e)}")
        return False

def _run_library_specific_scripts():
    """执行特定库的额外配置脚本"""
    print("开始执行特定库的额外配置...")

    # 获取当前库名
    current_library = _get_current_library_name()
    if not current_library:
        print("无法确定当前库名，跳过特定配置")
        return

    # 将当前库名转为小写，用于不区分大小写的匹配
    current_library_lower = current_library.lower()
    print(f"当前处理的库: {current_library}")

    # 获取当前工作目录
    current_dir = os.getcwd()

    # 处理mqtt库 - 当组件名匹配时执行
    if "mqtt" in current_library_lower:
        print(f"正在为库 {current_library} 执行MQTT特定配置...")

        # 1. 复制thirdparty文件夹
        mqtt_thirdparty_src = os.path.join(os.path.dirname(os.path.dirname(current_dir)), 'reply', 'mqtt', 'thirdparty')
        mqtt_thirdparty_dest = os.path.join(current_dir, 'ohos_Mqtt', 'src', 'main', 'cpp', 'thirdparty')

        if os.path.exists(mqtt_thirdparty_src):
            try:
                # 判断目标是否已经存在
                if not os.path.exists(mqtt_thirdparty_dest):
                    os.makedirs(mqtt_thirdparty_dest, exist_ok=True)
                    shutil.copytree(mqtt_thirdparty_src, mqtt_thirdparty_dest, dirs_exist_ok=True)
                    print(f"成功复制thirdparty文件夹到 {mqtt_thirdparty_dest}")
                else:
                    print(f"MQTT thirdparty目标目录已存在: {mqtt_thirdparty_dest}，跳过复制")
            except Exception as e:
                print(f"复制thirdparty文件夹时出错: {str(e)}")
        else:
            print(f"警告：找不到MQTT thirdparty源目录: {mqtt_thirdparty_src}")

        # 2. 执行modify.sh脚本
        mqtt_path = os.path.join(current_dir, 'ohos_Mqtt', 'src', 'main', 'cpp', 'paho.mqtt.c')
        if os.path.exists(mqtt_path):
            try:
                # 保存当前目录
                current_dir = os.getcwd()
                # 切换到mqtt目录
                os.chdir(mqtt_path)
                
                # 检查标记文件是否存在，避免重复执行
                marker_file = os.path.join(mqtt_path, '.modify_done')
                if os.path.exists('modify.sh') and not os.path.exists(marker_file):
                    # 使用subprocess执行脚本，并处理可能的交互
                    import subprocess
                    import time

                    # 启动脚本进程
                    from utils.config import GIT_PATH
                    process = subprocess.Popen([GIT_PATH, '-c', 'sh ./modify.sh'],
                                               stdin=subprocess.PIPE,
                                               stdout=subprocess.PIPE,
                                               stderr=subprocess.PIPE,
                                               universal_newlines=True,
                                               shell=True,
                                               creationflags=subprocess.CREATE_NEW_CONSOLE)
                    # 获取最终结果
                    stdout, stderr = process.communicate()
                    if stdout:
                        print(stdout)
                    if stderr:
                        print(f"执行脚本时出现警告或错误: {stderr}")
                    else:
                        # 脚本执行成功，创建标记文件
                        with open(marker_file, 'w') as f:
                            f.write('done')

                    print("modify.sh脚本执行完成")
                else:
                    print(f"警告：找不到mqtt库的modify.sh脚本: {mqtt_path}")

                # 3. 修改CMakeLists.txt文件
                cmake_file = os.path.join(mqtt_path, 'CMakeLists.txt')
                if os.path.exists(cmake_file):
                    try:
                        # 读取CMakeLists.txt文件
                        with open(cmake_file, 'r', encoding='utf-8') as f:
                            cmake_content = f.read()

                        # 要添加的内容
                        ssl_config = """
#开启ssl
add_definitions(-DOPENSSL)
#将三方库加入工程中
target_link_libraries(pahomqttc PRIVATE ${NATIVERENDER_ROOT_PATH}/thirdparty/openssl/${OHOS_ARCH}/lib/libssl.a)
target_link_libraries(pahomqttc PRIVATE ${NATIVERENDER_ROOT_PATH}/thirdparty/openssl/${OHOS_ARCH}/lib/libcrypto.a)

#将三方库的头文件加入工程中
target_include_directories(pahomqttc PRIVATE ${NATIVERENDER_ROOT_PATH}/thirdparty/openssl/${OHOS_ARCH}/include)
"""

                        # 检查是否已经添加了SSL配置
                        if "add_definitions(-DOPENSSL)" not in cmake_content:
                            # 在文件末尾添加SSL配置
                            with open(cmake_file, 'a', encoding='utf-8') as f:
                                f.write(ssl_config)
                            print(f"成功在 {cmake_file} 中添加SSL配置")
                        else:
                            print(f"{cmake_file} 中已存在SSL配置，无需添加")
                    except Exception as e:
                        print(f"修改CMakeLists.txt文件时出错: {str(e)}")
                else:
                    print(f"警告：找不到CMakeLists.txt文件: {cmake_file}")
            except Exception as e:
                print(f"处理mqtt库时出错: {str(e)}")
            finally:
                # 确保返回原始目录
                os.chdir(current_dir)
        else:
            print(f"警告：找不到mqtt库目录: {mqtt_path}")

    # 处理smack库 - 当组件名匹配时执行
    elif "smack" in current_library_lower:
        print(f"正在为库 {current_library} 执行COAP特定配置...")
        smack_path = os.path.join(current_dir, 'library', 'src', 'main', 'cpp', 'thirdModule')
        if os.path.exists(smack_path):
            try:
                # 保存当前目录
                current_dir = os.getcwd()
                # 切换到smack目录
                os.chdir(smack_path)
                # 检查标记文件是否存在，避免重复执行
                marker_file = os.path.join(smack_path, '.modify_done')
                if os.path.exists('modify.sh') and not os.path.exists(marker_file):
                    # 使用subprocess执行脚本，并处理可能的交互
                    import subprocess
                    import time

                    # 启动脚本进程
                    from utils.config import GIT_PATH
                    process = subprocess.Popen([GIT_PATH, '-c', 'sh ./modify.sh'],
                                               stdin=subprocess.PIPE,
                                               stdout=subprocess.PIPE,
                                               stderr=subprocess.PIPE,
                                               universal_newlines=True,
                                               shell=True,
                                               creationflags=subprocess.CREATE_NEW_CONSOLE)

                    # 获取最终结果
                    stdout, stderr = process.communicate()
                    if stdout:
                        print(stdout)
                    if stderr:
                        print(f"执行脚本时出现警告或错误: {stderr}")
                    else:
                        # 脚本执行成功，创建标记文件
                        with open(marker_file, 'w') as f:
                            f.write('done')
                    print("成功执行smack库的modify.sh脚本")
                else:
                    print(f"警告：找不到smack库的modify.sh脚本: {smack_path}")
            except Exception as e:
                print(f"处理smack库时出错: {str(e)}")
            finally:
                # 确保返回原始目录
                os.chdir(current_dir)
        else:
            print(f"警告：找不到smack库目录: {smack_path}")

    # 处理coap库 - 当组件名匹配时执行
    elif "coap" in current_library_lower:
        print(f"正在为库 {current_library} 执行COAP特定配置...")
        coap_path = os.path.join(current_dir, 'libcoap', 'src', 'main', 'cpp', 'thirdModule')
        if os.path.exists(coap_path):
            try:
                # 保存当前目录
                current_dir = os.getcwd()
                # 切换到coap目录
                os.chdir(coap_path)
                # 检查标记文件是否存在，避免重复执行
                marker_file = os.path.join(coap_path, '.modify_done')
                if os.path.exists('modify.sh') and not os.path.exists(marker_file):
                    # 使用subprocess执行脚本，并处理可能的交互
                    import subprocess
                    import time

                    # 启动脚本进程
                    from utils.config import GIT_PATH
                    process = subprocess.Popen([GIT_PATH, '-c', 'sh ./modify.sh'],
                                               stdin=subprocess.PIPE,
                                               stdout=subprocess.PIPE,
                                               stderr=subprocess.PIPE,
                                               universal_newlines=True,
                                               shell=True,
                                               creationflags=subprocess.CREATE_NEW_CONSOLE)

                    # 获取最终结果
                    stdout, stderr = process.communicate()
                    if stdout:
                        print(stdout)
                    if stderr:
                        print(f"执行脚本时出现警告或错误: {stderr}")
                    else:
                        # 脚本执行成功，创建标记文件
                        with open(marker_file, 'w') as f:
                            f.write('done')
                    print("成功执行coap库的modify.sh脚本")
                else:
                    print(f"警告：找不到coap库的modify.sh脚本: {coap_path}")
            except Exception as e:
                print(f"处理coap库时出错: {str(e)}")
            finally:
                # 确保返回原始目录
                os.chdir(current_dir)
        else:
            print(f"警告：找不到coap库目录: {coap_path}")

    # 处理aki库 - 当组件名匹配时执行
    elif "publish" in current_library_lower:
        print(f"正在为库 {current_library} 执行AKI等库特定配置...")
        from utils.config import selected_sdk_version, selected_api_version
        _modify_build_profile(selected_sdk_version, selected_api_version)
        
    # 处理ijkplayer库 - 当组件名匹配时执行
    elif "ijkplayer" in current_library_lower:
        print(f"正在为库 {current_library} 执行IJKPlayer特定配置...")
        ijkplayer_src = os.path.join(os.path.dirname(os.path.dirname(current_dir)), 'reply', 'ijkplayer')
        ijkplayer_dest = os.path.join(current_dir, 'ijkplayer', 'src', 'main', 'cpp', 'third_party')

        if os.path.exists(ijkplayer_src) and os.path.exists(ijkplayer_dest):
            try:
                # 拷贝ffmpeg到third_party/ffmpeg，并确保ffmpeg目录嵌套
                ffmpeg_src = os.path.join(ijkplayer_src, 'ffmpeg')
                ffmpeg_dest_dir = os.path.join(ijkplayer_dest, 'ffmpeg')
                ffmpeg_dest_path = os.path.join(ffmpeg_dest_dir, 'ffmpeg')

                if os.path.exists(ffmpeg_src):
                    if not os.path.exists(ffmpeg_dest_path):
                        os.makedirs(ffmpeg_dest_dir, exist_ok=True)
                        shutil.copytree(ffmpeg_src, ffmpeg_dest_path, dirs_exist_ok=True)
                        print(f"成功拷贝ffmpeg到 {ffmpeg_dest_path}")
                    else:
                        print(f"ffmpeg目录已存在: {ffmpeg_dest_path}，跳过复制")
                else:
                    print(f"警告：找不到ffmpeg源目录: {ffmpeg_src}")

                # 拷贝其他库到third_party
                for lib in ['openssl', 'soundtouch', 'yuv', 'openh264']:
                    lib_src = os.path.join(ijkplayer_src, lib)
                    lib_dest = os.path.join(ijkplayer_dest, lib)

                    if os.path.exists(lib_src):
                        if not os.path.exists(lib_dest):
                            shutil.copytree(lib_src, lib_dest, dirs_exist_ok=True)
                            print(f"成功拷贝{lib}到 {lib_dest}")
                        else:
                            print(f"{lib}目录已存在: {lib_dest}，跳过复制")
                    else:
                        print(f"警告：找不到{lib}源目录: {lib_src}")
            except Exception as e:
                print(f"处理ijkplayer库时出错: {str(e)}")
        else:
            print(f"警告：找不到ijkplayer源目录或目标目录: 源={ijkplayer_src}, 目标={ijkplayer_dest}")


    # 处理libpag库 - 当组件名匹配时执行
    elif "libpag" in current_library_lower:
        print(f"正在为库 {current_library} 执行libpag特定配置...")
        libpag_src = os.path.join(os.path.dirname(os.path.dirname(current_dir)), 'reply', 'libpag')
        libpag_dest = os.path.join(current_dir, 'library')

        if os.path.exists(libpag_src) and os.path.exists(libpag_dest):
            try:
                # 拷贝libs到library/
                libs_src = os.path.join(libpag_src, 'libs')
                libs_dest = os.path.join(libpag_dest)

                if os.path.exists(libs_src):
                    if not os.path.exists(libs_dest):
                        shutil.copytree(libs_src, libs_dest, dirs_exist_ok=True)
                        print(f"成功拷贝libs到 {libs_dest}")
                    else:
                        print(f"libs目标目录已存在: {libs_dest}，跳过复制")
                else:
                    print(f"警告：找不到libs源目录: {libs_src}")

                # 拷贝其他库到thirdparty
                lib_src = os.path.join(libpag_src, 'lib')
                lib_dest = os.path.join(libpag_dest, 'src', 'main', 'cpp', 'thirdparty', 'pag', 'arm64-v8a')

                if os.path.exists(lib_src):
                    if not os.path.exists(lib_dest):
                        shutil.copytree(lib_src, lib_dest, dirs_exist_ok=True)
                        print(f"成功拷贝lib到 {lib_dest}")
                    else:
                        print(f"lib目标目录已存在: {lib_dest}，跳过复制")
                else:
                    print(f"警告：找不到lib源目录: {lib_src}")

            except Exception as e:
                print(f"处理libpag库时出错: {str(e)}")
        else:
            print(f"警告：找不到libpag源目录或目标目录: 源={libpag_src}, 目标={libpag_dest}")

    # 处理luaarkts库 - 当组件名匹配时执行
    elif "luaarkts" in current_library_lower:
        print(f"正在为库 {current_library} 执行luaarkts特定配置...")
        luaarkts_src = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(current_dir))), 'reply', 'luaarkts')
        luaarkts_dest = os.path.join(current_dir, 'luaarkts', 'src', 'main', 'cpp')

        if os.path.exists(luaarkts_src) and os.path.exists(luaarkts_dest):
            try:
                # 拷贝LuaJIT到thirdparty
                luajit_src = os.path.join(luaarkts_src)
                luajit_dest = os.path.join(luaarkts_dest, 'thirdparty')
                if os.path.exists(luajit_src):
                    if not os.path.exists(luajit_dest):
                        os.makedirs(luajit_dest, exist_ok=True)
                        shutil.copytree(luajit_src, luajit_dest, dirs_exist_ok=True)
                        print(f"成功拷贝LuaJIT到 {luajit_dest}")
                    else:
                        print(f"LuaJIT目标目录已存在: {luajit_dest}，跳过复制")
                else:
                    print(f"警告：找不到LuaJIT源目录: {luajit_src}")
            except Exception as e:
                print(f"处理luaarkts库时出错: {str(e)}")
        else:
            print(f"警告：找不到luaarkts源目录或目标目录: 源={luaarkts_src}, 目标={luaarkts_dest}")


    elif "grpc" in current_library_lower:
        print(f"正在为库 {current_library} 执行GRPC特定配置...")
        grpc_src = os.path.join(os.path.dirname(os.path.dirname(current_dir)), 'reply', 'grpc')
        grpc_dest = os.path.join(current_dir, 'library', 'src', 'main', 'cpp', 'thirdparty')

        if os.path.exists(grpc_src) and os.path.exists(grpc_dest):
            try:
                for lib in ['json', 'nghttp2', 'openssl_quic']:
                    lib_src = os.path.join(grpc_src, lib)
                    lib_dest = os.path.join(grpc_dest, lib)

                    if os.path.exists(lib_src):
                        if not os.path.exists(lib_dest):
                            shutil.copytree(lib_src, lib_dest, dirs_exist_ok=True)
                            print(f"成功拷贝{lib}到 {lib_dest}")
                        else:
                            print(f"{lib}目标目录已存在: {lib_dest}，跳过复制")
                    else:
                        print(f"警告：找不到{lib}源目录: {lib_src}")

                    # 注释json库include\nlohmann\detail\output\serializer.hpp：513行的代码
                    if lib == 'json':
                        serializer_file = os.path.join(lib_dest, 'arm64-v8a', 'include', 'nlohmann', 'detail', 'output', 'serializer.hpp')
                        if os.path.exists(serializer_file):
                            with open(serializer_file, 'r', encoding='utf-8') as f:
                                lines = f.readlines()
                            with open(serializer_file, 'w', encoding='utf-8') as f:
                                for line in lines:
                                    if line.strip() == 'JSON_THROW(type_error::create(316, concat("invalid UTF-8 byte at index ", std::to_string(i), ": 0x", hex_bytes(byte | 0)), nullptr));':
                                        f.write('// ' + line)
                                    else:
                                        f.write(line)
                            print(f"成功注释掉{serializer_file}的第513行代码")
            except Exception as e:
                print(f"处理grpc库时出错: {str(e)}")
        else:
            print(f"警告：找不到grpc源目录或目标目录: 源={grpc_src}, 目标={grpc_dest}")

    # 处理mars库 - 当组件名匹配时执行
    elif "mars" in current_library_lower:
        print(f"正在为库 {current_library} 执行mars特定配置...")
        mars_src = os.path.join(os.path.dirname(os.path.dirname(current_dir)), 'reply', 'mars')
        mars_dest = os.path.join(current_dir, 'library', 'src', 'main', 'cpp', 'thirdparty')

        try:
            # 拷贝openssl到thirdparty
            if os.path.exists(mars_src):
                if not os.path.exists(mars_dest):
                    os.makedirs(mars_dest, exist_ok=True)
                    shutil.copytree(mars_src, mars_dest, dirs_exist_ok=True)
                    print(f"成功拷贝openssl到 {mars_dest}")
                else:
                    print(f"openssl目标目录已存在: {mars_dest}，跳过复制")

                # 执行mars patch脚本
                script_path = os.path.join(current_dir, 'automatically_apply_mars_patch_files.sh')
                if os.path.exists(script_path):
                    try:
                        # 检查标记文件是否存在，避免重复执行
                        marker_file = os.path.join(current_dir, '.mars_patch_done')
                        if not os.path.exists(marker_file):
                            # 使用Popen执行脚本，并处理可能的交互
                            import subprocess
                            process = subprocess.Popen([config.GIT_PATH, '-c', f'cd {current_dir} && chmod +x automatically_apply_mars_patch_files.sh && ./automatically_apply_mars_patch_files.sh'],
                                                     stdin=subprocess.PIPE,
                                                     stdout=subprocess.PIPE,
                                                     stderr=subprocess.PIPE,
                                                     universal_newlines=True,
                                                     shell=True,
                                                     creationflags=subprocess.CREATE_NEW_CONSOLE)
                            
                            # 获取最终结果
                            stdout, stderr = process.communicate()
                            if stdout:
                                print(stdout)
                            if stderr:
                                print(f"执行脚本时出现警告或错误: {stderr}")
                            else:
                                # 脚本执行成功，创建标记文件
                                with open(marker_file, 'w') as f:
                                    f.write('done')
                            print("成功执行mars patch脚本")
                        else:
                            print("mars patch脚本已执行过，跳过")
                    except Exception as e:
                        print(f"处理mars patch脚本时出错: {str(e)}")
                else:
                    print(f"警告：找不到mars patch脚本: {script_path}")
            else:
                print(f"警告：找不到openssl源目录: {mars_src}")
        except Exception as e:
            print(f"处理mars库时出错: {str(e)}")

    # 处理mp4parser库 - 当组件名匹配时执行
    elif "mp4parser" in current_library_lower:
        print(f"正在为库 {current_library} 执行mp4parser特定配置...")
        mp4parser_src = os.path.join(os.path.dirname(os.path.dirname(current_dir)), 'reply', 'mp4parser')
        mp4parser_dest = os.path.join(current_dir, 'library')

        if os.path.exists(mp4parser_src) and os.path.exists(mp4parser_dest):
            try:
                # 拷贝libs到thirdparty
                libs_src = os.path.join(mp4parser_src, 'libs')
                libs_dest = os.path.join(mp4parser_dest, 'libs')
                if os.path.exists(libs_src):
                    if not os.path.exists(libs_dest):
                        os.makedirs(libs_dest, exist_ok=True)
                        shutil.copytree(libs_src, libs_dest, dirs_exist_ok=True)
                        print(f"成功拷贝libs到 {libs_dest}")
                    else:
                        print(f"libs目标目录已存在: {libs_dest}，跳过复制")
                else:
                    print(f"警告：找不到libs源目录: {libs_src}")

                # 拷贝thirdparty到cpp目录下
                third_party_src = os.path.join(mp4parser_src, 'third_party')
                third_party_dest = os.path.join(mp4parser_dest, 'src', 'main', 'cpp', 'third_party')
                if os.path.exists(third_party_src):
                    if not os.path.exists(third_party_dest):
                        os.makedirs(third_party_dest, exist_ok=True)
                        shutil.copytree(third_party_src, third_party_dest, dirs_exist_ok=True)
                        print(f"成功拷贝third_party到 {third_party_dest}")
                    else:
                        print(f"third_party目标目录已存在: {third_party_dest}，跳过复制")
                else:
                    print(f"警告：找不到third_party源目录: {third_party_src}")
            except Exception as e:
                print(f"处理mp4parser库时出错: {str(e)}")

    else:
        print(f"当前库 {current_library} 不需要执行特定配置脚本")
    print("特定库配置执行完成")


def clean_json5_content(content):
    """清理 JSON5 内容，移除注释和尾部逗号"""
    # 移除注释行
    content_no_comments = re.sub(r'//.*?\n', '\n', content)
    # 移除尾部逗号
    content_no_comments = re.sub(r',(\s*[}\]])', r'\1', content_no_comments)
    return content_no_comments